/*
 * Copyright 1999-2015 dangdang.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */

package com.bicon.botu.mall.order.processor.task.schedule;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.mall.base.rpc.service.SystemConfigRpcService;
import com.bicon.botu.mall.order.cache.RedisLock;
import com.bicon.botu.mall.order.common.CollectEnum;
import com.bicon.botu.mall.order.common.OrderConstans;
import com.bicon.botu.mall.order.dto.MallConfigDto;
import com.bicon.botu.mall.order.entity.OrderGoods;
import com.bicon.botu.mall.order.service.IOrderDeliverService;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 过期自动收货
 * @author  jwj
 * @date    2018-06-19
 */
@Slf4j
//@ElasticJobConf(name = "CollectOrderJob")
public class CollectOrderJob implements SimpleJob {

    private static final String lock = "collect_order_task_lock";

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private SystemConfigRpcService systemConfigRpcService;

    @Autowired
    private IOrderDeliverService iOrderDeliverService;

    @Override
    public void execute(final ShardingContext shardingContext) {

        long lockTimeOut = redisLock.lock(lock,4000);
        String params = shardingContext.getShardingParameter();

        if (lockTimeOut <= 0) {
            log.info("自动收货分片：" + params + ",上一次任务未执行完毕");
            return;
        }
        BaseResult baseResult = systemConfigRpcService.getOderConfigValue(OrderConstans.CINFIRM_RECEIPT);
        log.info("分片：" + params + ",获取自动收货的配置：" + JSONObject.toJSONString(baseResult));
        if (baseResult.getCode() == Constants.RESPONSE_CODE_200) {
            MallConfigDto mallConfigDto = JSONObject.parseObject(JSONObject.toJSONString(baseResult.getData()), MallConfigDto.class);
            int timeLength = CollectEnum.valueOf(mallConfigDto.getDictionaryValue()).getTimeLength();
            if (timeLength > 0) {
                List<OrderGoods> orderGoodsList = new OrderGoods().selectList(new EntityWrapper<OrderGoods>().eq("pay_state", OrderConstans.ORDER_STATUS_3)
                        .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).andNew("TIMESTAMPDIFF(DAY, update_date, now()) > {0}", timeLength));
                int resNum = 0;
                int errorNum = 0;
                log.info("分片：" + params + ",自动收货开始");
                for(OrderGoods goods : orderGoodsList) {
                    try {
                        iOrderDeliverService.orderCompletion(goods.getId(),"");
                        resNum++;
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        errorNum++;
                    }
                }
                log.info("自动收货分片：" + params + ",成功处理：" + resNum + ", 出现错误:" + errorNum);
            }
        }
        // 释放锁
        redisLock.releaseLock(lock,lockTimeOut);
    }
}
